package com.eportal.service.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.eportal.base.BaseDAO;
import com.eportal.domain.CommunityMsg;
import com.eportal.service.CommunityMsgService;
import com.framework.jqgrid.JqGridPager;

@Service("communityMsgService")
public class CommunityMsgServiceImpl  implements CommunityMsgService{
	
	@Resource(name="dao")
	private BaseDAO dao;
	private Logger log = Logger.getLogger(CommunityMsgServiceImpl.class);
	private Map<String, Object> result = new HashMap<String, Object>();
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Override
	public CommunityMsg get(Long sid){
		CommunityMsg communityMsg = (CommunityMsg)dao.getById(CommunityMsg.class, sid);
		return communityMsg;
	}
	
	@Override
	public List<Map<String, Object>> list(JqGridPager jqGridPager) {
		String sql ="select cm.sid,c.communityname,cm.cmsg,cm.receiver,TO_CHAR (cm.ctime,'yyyy-MM-dd HH24:mi:ss') as ctime from t033_community_msg cm"
				+ " left join t03_community c on cm.communityid=c.sid";
		List<Map<String, Object>> list =  dao.query(sql, jqGridPager);
		if(list.isEmpty() || list.size()<1){
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			String rUser = (String) list.get(i).get("receiver");
			if("*".equals(rUser)){
				continue;
			}else{
				String[] arrIds = rUser.split(",");
				final List<Long> tmp2 = new LinkedList<Long>();
    			for (int j = 0; j < arrIds.length; j++) {
    				tmp2.add(Long.parseLong(arrIds[j]));
				}
    			String comusql = "select uname from Sysopt where sid in (:ids)";
    			List<String> listUName = dao.executeFind(comusql,"ids",tmp2);
    			String uName = org.apache.commons.lang.StringUtils.join(listUName.toArray(),",");
    			list.get(i).put("receiver", uName);
			}
		}
		return list;
	}

	
	
	public CommunityMsg save(CommunityMsg communityMsg) throws Exception {
    	dao.save(communityMsg);
    	return communityMsg;
    }

	
}
